<!DOCTYPE html>
<html lang='en'>
<head>
	<meta charset='UTF-8' />
	<meta name="viewport" content="width=device-width, initial-scale=1.0, minimum-scale=1.0, maximum-scale=1.0,user-scalable=no">
	<title>HTML5 拍照</title>
</head>
<body>

	<video id="video" autoplay style="width:480px;height:320px"></video><!-- 显示MediaStream视频流 -->
	<div><button id="capture">拍照</button></div>
	<canvas id="canvas" width="480" height="320"></canvas>
	<script type="text/javascript">


    // 访问用户媒体设备的兼容方法
    function getUserMedia(constraints, success, error) {
      if (navigator.mediaDevices.getUserMedia) {
        // 最新的标准API
        navigator.mediaDevices.getUserMedia(constraints)
        .then(success).catch(error);
      } else if (navigator.webkitGetUserMedia) {
        // Webkit核心浏览器
        navigator.webkitGetUserMedia(constraints, success, error);
      } else 
      if (navigator.mozGetUserMedia) {
        // Firefox浏览器
        navigator.mozGetUserMedia(constraints, success, error);
      } else if (navigator.getUserMedia) {
        // 旧版API
        navigator.getUserMedia(constraints, success, error);
      }
    }
		var video = document.getElementById("video");// video元素
    var canvas = document.getElementById("canvas");// canvas元素
		var context = canvas.getContext("2d");

    // 成功的回调函数
    function success(stream) {
      var CompatibleURL = window.URL || window.webkitURL
      video.src = CompatibleURL.createObjectURL(stream);//将视频流设置为video元素的源
      video.play();// 播放视频
    }

    // 异常的回调函数
    function error(error) {
			console.log('访问用户媒体设备失败：', error.name, error.message);
		}

    if (navigator.mediaDevices.getUserMedia || navigator.getUserMedia ||
        navigator.webkitGetUserMedia || navigator.mozGetUserMedia) {
      // 调用用户媒体设备，访问摄像头
      getUserMedia({ video: { width: 480, height: 320 } }, success, error);
    } else {
      alert('您的浏览器不支持访问用户媒体设备！');
    }

    // 绑定拍照按钮的点击事件
		document.getElementById("capture").addEventListener("click", function () {
			context.drawImage(video, 0, 0, 480, 320);// 将video画面在canvas上绘制出来
		});
	</script>
</body>
</html>